package basic

import (
	"fmt"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"gopkg.in/natefinch/lumberjack.v2"
	"os"
)

var zapLogger *zap.Logger

type Logger struct {
}

func init() {
	zapLogger = zap.New(initCore(), zap.AddCaller(), zap.AddCallerSkip(1))
	defer zapLogger.Sync()
}

func initCore() zapcore.Core {

	// 2. 配置编码器
	encoderConfig := zapcore.EncoderConfig{
		TimeKey:        "time",
		LevelKey:       "level",
		NameKey:        "logger",
		CallerKey:      "caller",
		FunctionKey:    zapcore.OmitKey,
		MessageKey:     "msg",
		StacktraceKey:  "stacktrace",
		LineEnding:     zapcore.DefaultLineEnding,
		EncodeLevel:    zapcore.LowercaseLevelEncoder,
		EncodeTime:     zapcore.ISO8601TimeEncoder,
		EncodeDuration: zapcore.StringDurationEncoder,
		EncodeCaller:   zapcore.ShortCallerEncoder,
	}

	// 替换之前的文件创建代码
	fileCore := zapcore.NewCore(
		zapcore.NewJSONEncoder(encoderConfig),
		zapcore.AddSync(&lumberjack.Logger{
			Filename:   "C:/Users/nixgn/Downloads/logs/learn-protobuf.log", // 日志文件路径
			MaxSize:    100,                                                // 每个日志文件的最大大小(MB)
			MaxBackups: 100,                                                // 保留的旧日志文件最大数量
			MaxAge:     1,                                                  // 保留旧日志文件的最大天数
			Compress:   false,                                              // 是否压缩/归档旧日志文件
		}),
		zapcore.DebugLevel,
	)

	// 4. 可选: 同时输出到控制台
	consoleEncoder := zapcore.NewConsoleEncoder(encoderConfig)
	consoleCore := zapcore.NewCore(
		consoleEncoder,
		zapcore.AddSync(os.Stdout),
		zapcore.DebugLevel,
	)

	// 5. 使用多核心
	core := zapcore.NewTee(
		fileCore,
		consoleCore, // 注释掉这行则只输出到文件
	)
	return core
}
func (logger *Logger) Info(format string, a ...any) {
	zapLogger.Info(fmt.Sprintf(format, a))
}

func (logger *Logger) ERROR(format string, a ...any) {
	zapLogger.Error(fmt.Sprintf(format, a))
}

func (logger *Logger) WARN(format string, a ...any) {
	zapLogger.Warn(fmt.Sprintf(format, a))
}
